var url = "/openx/logistics/deliverytype/listDeliveryType",
  formId = "queryForm",
  param = {},
  providerRulePageNumber = 1,
    providerRulePageSize = 10
;

(function () {
  param.topChannelCode = "";
  var fromdata = $.extend({}, param, $.openx.getJsonObj(formId));
  $.openx.initTable("table", url, fromdata);
  $.openx.setTableToolBar("partnerbar"); //设置工具栏
})();

$.openx.query = function () {
  var fromdata = $.extend({}, param, $.openx.getJsonObj(formId));
  $.openx.tableRefresh(url, fromdata);
};

function isDefault(v, row) {
  return v ? "是" : "否";
}

// 数字转字符串不足两位补0
const numToStringByAddZeroUtil = (num) => (num < 10 ? `0${num}` : `${num}`);

// 字符串转数字（空字符串不处理）
const convertStringToNum = (str) => (str ? +str : str);

// 时分秒转化为数字 - 仅用于比较
const convertTimeToNumUtil = (time) =>
  +new Date(`2021/05/13 ${time}`);

/**
 * 判断是否存在交叉时间段
 */
const isCrossTimeRangeUtil = (arr) => {
  const newArr = [];
  // 根据是否跨天来拆分
  arr.forEach((item) => {
    // 跨天则拆分
    if (
      convertTimeToNumUtil(item.startTime) > convertTimeToNumUtil(item.endTime)
    ) {
      newArr.push({
        startTime: convertTimeToNumUtil(item.startTime),
        endTime: convertTimeToNumUtil('23:59:59')
      }, {
        startTime: convertTimeToNumUtil('00:00:00'),
        endTime: convertTimeToNumUtil(item.endTime)
      })
    } else {
      newArr.push({
        startTime: convertTimeToNumUtil(item.startTime),
        endTime: convertTimeToNumUtil(item.endTime)
      })
    }
  });
  // 重新分组排序
  const sortArr = newArr.reduce((prev, curr, index) => {
    return prev.concat([
      { index, time: curr.startTime },
      { index, time: curr.endTime },
    ]);
  }, [])
    .sort((x, y) => x.time - y.time);
  // 判断相邻 - index为奇数项时，当前与上一个不属于同一组，或下一个 time 值相同，则判定为重叠
  return sortArr.some((item, index) =>
    index % 2
      ? item.index !== sortArr[index - 1].index ||
      (sortArr[index + 1] && item.time === sortArr[index + 1].time)
      : false
  );
};

// 转换通用配置苏剧格式为服务端需要的数据格式
const convertCommonProviderToInfoUtil = (formData, deliveryTypeId, topChannelCode) => {
  if (!(formData.length > 0)) {
    return [];
  }
  // scrambleType
  const { providers = [], scrambleType } = formData[0];
  return providers.map(m => (Object.assign({}, {
    sortNum: 1,
    topChannelCode,
    providerCode: m.company,
    range: convertStringToNum(m.range),
    interval: convertStringToNum(m.waitingTime),
    createTime: '',
    modifyTime: '',
    scrambleType
  }, deliveryTypeId ? { deliveryTypeId } : {})));
}

// 服务端得到的通用物流配置数据格式转换成本地需要得表单数据格式
const convertCommonProviderInfosToFormUtil = (infos) => {
  if (!(infos && infos.length > 0)) {
    return [];
  }
  return {
    scrambleType: infos[0].scrambleType || '',
    providers: infos.map(item => ({
      company: item.providerCode,
      range: item.range,
      waitingTime: item.interval
    }))
  }
};

// 转换表单 物流配置数据格式为服务端需要的数据格式
const convertProviderFormToInfosUtil = (formData, deliveryTypeId) =>
  formData.reduce((total, curr) => {
    const currArr = [];
    curr.channels.forEach((k) => {
      curr.times.forEach((j) => {
        j.providers.forEach((m) => {
          currArr.push(
            Object.assign(
              {},
              {
                sortNum: curr.sortNum,
                channelCode: k.channelCode,
                channelName: k.channelName,
                startTime: j.startTime,
                endTime: j.endTime,
                scrambleType: j.scrambleType,
                providerCode: m.company,
                range: convertStringToNum(m.range),
                interval: convertStringToNum(m.waitingTime),
              },
              deliveryTypeId ? { deliveryTypeId } : {}
            )
          );
        });
      });
    });
    return total.concat(currArr);
  }, []);

// 服务端得到得物流配置数据格式转换成本地需要得表单数据格式
const convertProviderInfosToFormUtil = (infos) => {
  const formObj = infos.reduce((total, curr) => {
    const {
      channelCode,
      channelName,
      startTime,
      endTime,
      scrambleType,
      providerCode,
      range = "",
      interval = "",
    } = curr;
    const obj = total;
    if (obj[curr.sortNum]) {
      // channels 数组保证子项唯一
      if (
        !obj[curr.sortNum].channels.some((h) => h.channelCode === channelCode)
      ) {
        obj[curr.sortNum].channels.push({ channelCode, channelName });
      }
      if (obj[curr.sortNum].times[`${startTime}-${endTime}`]) {
        // providers 数组保证 子项唯一
        if (
          !obj[curr.sortNum].times[`${startTime}-${endTime}`].providers.some(
            (v) => v.company === providerCode && v.range === range && v.waitingTime === interval
          )
        ) {
          obj[curr.sortNum].times[`${startTime}-${endTime}`].providers.push({
            company: providerCode,
            range,
            waitingTime: interval,
          });
        }
      } else {
        obj[curr.sortNum].times[`${startTime}-${endTime}`] = {
          startTime,
          endTime,
          scrambleType,
          providers: [{ company: providerCode, range, waitingTime: interval }],
        };
      }
    } else {
      obj[curr.sortNum] = {
        sortNum: curr.sortNum,
        channels: [{ channelCode, channelName }],
        times: {
          [`${startTime}-${endTime}`]: {
            startTime,
            endTime,
            scrambleType,
            providers: [
              { company: providerCode, range, waitingTime: interval },
            ],
          },
        },
      };
    }
    return obj;
  }, {});

  return Object.keys(formObj).map((k) =>
    Object.assign({}, formObj[k], {
      times: Object.keys(formObj[k].times).map(
        (timesKey) => formObj[k].times[timesKey]
      ),
    })
  );
};

// 物流策略初始表单值
const INIT_PROVIDER_CONFIG_PROVIDER = {
  company: "",
  range: "",
  waitingTime: "",
};
const INIT_PROVIDER_CONFIG_TIME = {
  startTime: "",
  endTime: "",
  scrambleType: "",
  providers: [INIT_PROVIDER_CONFIG_PROVIDER],
};
const INIT_PROVIDER_CONFIG_CHILD_CHANNEL = {
  channels: [],
  times: [INIT_PROVIDER_CONFIG_TIME],
};

// 抢单方式
const ROB_RADIOS = [
  { value: 'CLOSE', label: '不开启' },
  { value: 'LOOPOPEN', label: '轮询后开启' },
  { value: 'OPEN', label: '仅开启抢单' }
];

// 一些常量
const BASIC_CONSTANTS = {
  commonConfigChannelId: 'virtual-id-common-channel',
  comminConfigChannelTimeId: 'virtual-id-common-channel-time'
}

function statusFormat(v, row) {
  var id = row.id + new Date().getTime();
  var html = '<div class="switch">';
  html += '<div class="onoffswitch">';
  if (row.status === "ENABLE") {
    html +=
      "<input type='checkbox'  checked class='onoffswitch-checkbox' onclick ='javascript:changeDeliveryStatus(" +
      JSON.stringify(row) +
      ")'  id='" +
      id +
      "'>";
  } else {
    html +=
      "<input type='checkbox'  class='onoffswitch-checkbox' onclick ='javascript:changeDeliveryStatus(" +
      JSON.stringify(row) +
      ")'  id='" +
      id +
      "'>";
  }
  html += '<label class="onoffswitch-label" for="' + id + '">';
  html += '<span class="onoffswitch-inner"></span>';
  html += '<span class="onoffswitch-switch"></span>';
  html += "</label>";
  html += "</div>";
  html += "</div>";
  return html;
}

function showProviderRuleListFormatter(v, row) {
  return (
    "<a href='javascript:void(0)' title='点击查看物流配置表' style = 'color:#000000;text-decoration:underline;' onclick ='javascript:showProviderRules(" +
    JSON.stringify(row) +
    ")'><b>" +
    row.topChannelName +
    "</b><a>"
  );
}

function showFormatScrambleType(v, row) {
   var scrambleType = "";
   if ("CLOSE" === row.scrambleType) {
      scrambleType = "不开启";
      return  scrambleType;
   }
  if ("LOOPOPEN" === row.scrambleType) {
    scrambleType = "轮询后开启";
    return  scrambleType;
  }
  if ("OPEN" === row.scrambleType) {
    scrambleType = "仅开启";
  }
  return  scrambleType;
}

// 表格 指定物流行自定义处理
function appointProviderRowFormatter(v, row) {
  const text = isDefault(row.appointProvider);
  if (!row.appointProvider) {
    return text;
  }
  return `<a href='javascript:void(0)' style = 'color:#23c888;text-decoration:underline;' onclick ='javascript:updateHandler(${JSON.stringify([row])},${JSON.stringify(true)})'>${text}</a>`
}

function changeDeliveryStatus(row) {
  $X("/logistics/deliverytype", "enableOrDisableDeliveryType").callx({
    id: row.id,
    onResult: function (data) {
      if (data) {
        $.openx.tableRefresh(null, null, true);
        layer.closeAll();
        layer.msg("修改成功");
      }
    },
    onError: function (error) {
      var res = JSON.parse(error);
      layer.msg(res.message);
    },
  });
}

function showProviderRules(row) {
  laytpl($.openx.innerHtml("providerRuleListTpl")).render(row, function (html) {
    var providerPluginsDiv = $("div[name='providerSelectsPluginsDiv']").html();
    var div = $(html);
    div.find("div[name='providerPluginsDiv']").html(providerPluginsDiv); // 设置物流供应商信息
    var index = $.openx.openLayer(null, "查询渠道物流策略", div.html(), true);
    var layuiLayer = $("#layui-layer" + index);
    layuiLayer.find(".layui-layer-content").height("500px");
  });
  initTable(row.id);
}

function initTable(deliveryTypeId) {
  providerRulePageNumber = 1;
  providerRulePageSize = 10;
  var url =
    ecp_boss_server + "/openx/logistics/lgtTypeProviderRuleService/listPage";
  var formParam = {};
  formParam.queryForm = { deliveryTypeId: deliveryTypeId };
  //封装分页对象 默认从第一条开始  每页10条
  var request = {};
  //layer.load();// 显示加载提示
  // 定义表格的默认样式
  request.queryParams = function (data) {
    var page = {};
    page.offset = data.offset;
    page.pageSize = data.limit;
    page.pageNum = parseInt(parseInt(data.offset) + parseInt(data.limit)) / parseInt(data.limit);
    formParam.page = page;
    formParam._openx_head = getOpenxHeader();
    return formParam;
  };
  $("#providerRuleTable").bootstrapTable({
    url: url,
    queryParams: request.queryParams,
    pagination: true,
    align: "center",
    striped: false,
    search: false,
    showToggle: false,
    pageNumber:providerRulePageNumber,
    pageSize:providerRulePageSize,
    pageList: [5, 10, 25, 50, 100],
    method: "post",
    showRefresh: false,
    silent: false,
    sidePagination: "server",
    showColumns: false,
    toolbar: "",
    iconSize: "outline",
    icons: {
      toggle: "glyphicon-list-alt",
      columns: "glyphicon-list",
      refresh: "glyphicon-refresh icon-refresh",
    },
    onPageChange: function (num, size) {
      providerRulePageNumber = num;
      providerRulePageSize  = size;
    },
    responseHandler: function (res) {
      return res;
    },
  });

  $("#providerRuleTable").on("click-row.bs.table", function (e, row, $element) {
    // 设置表格选择后的颜色
    $(".success").removeClass("success");
    $($element).addClass("success");
  });

  // 对应事件 onLoadSuccess
  $("#providerRuleTable").on(
    "load-success.bs.table",
    function (e, row, $element) {
      layer.closeAll("loading");
    }
  );

  //对应事件 onLoadError
  $("#providerRuleTable").on("load-error.bs.table", function (xhr, error) {
    layer.closeAll("loading");
    if (error && error.status && error.status === 500) {
      var errorJSON = error.responseJSON || null;
      if (errorJSON && errorJSON.code === "70009999") {
        layer.alert(
          errorJSON.message,
          {
            // skin: 'layui-layer-molv' //样式类名
            title: "登录信息",
            closeBtn: 0,
          },
          function () {
            location.href = "/login.html";
          }
        );
      }
    } else {
      layer.msg("数据加载失败,服务器出错");
    }
  });
}

function queryChannelProviderRuleList(deliveryTypeId) {
  var url =
    ecp_boss_server + "/openx/logistics/lgtTypeProviderRuleService/listPage";
  var formData = $.openx.getJsonObj("providerRuleListForm");
  var formParam = {};
  formParam.queryForm = {
    channelCode: formData.channelCode2,
    channelName: formData.channelName,
    operator: formData.operator,
    providerCode: formData.logisticsType,
    deliveryTypeId: deliveryTypeId,
  };
  $("#providerRuleTable").bootstrapTable("refresh", {
    url: url,
    query: formParam,
  });
}

function showTimeRangeFormat(v, row) {
  var startTime = row.startTime?row.startTime:'';
  var endTime = row.endTime?row.endTime:'';
  return startTime + "-" + endTime;
}

function dateFormat(value) {
  return !value ? "-" : new Date(value).format("yyyy-MM-dd hh:mm:ss")
}

function showProviderNameFormat(v, row) {
  return providerMap.get(row.providerCode);
}

$.openx.delete = function () {
  $.openx.onClickDelete(function (row) {
    $X("/logistics/deliverytype", "deleteDeliveryType").callx({
      id: row[0].id,
      onResult: function (data) {
        $.openx.tableRefresh(null, null, true);
        layer.msg("删除成功");
      },
      onError: function (error) {
        layer.msg("系统错误，请联系管理员");
      },
    });
  });
};

/**
 * 
 * @param {object} row 行数据，一维数组
 * @param {boolean} isEditProviderInfos 是否是编辑渠道物流公司信息
 */
function updateHandler(row, isEditProviderInfos = false) {
  var formId = "addDeliveryTypeForm";
  var innerHtml = $.openx.innerHtml("addUpdateTpl");
  laytpl(innerHtml).render(row[0], function (html) {
    var topchannelDiv = $("div[name='channelPluginsDiv']").html();
    var providerPluginsDiv = $(
      "div[name='providerSelectsPluginsDiv']"
    ).html();
    var div = $(html);
    div.find("div[name='topChannelTypeDiv']").html(topchannelDiv); // 设置渠道信息
    div.find("div[name='providerPluginsDiv']").html(providerPluginsDiv); // 设置物流供应商信息
    //初始化渠道
    div
      .find(
        "select[name='topChannelCode'] option[value='" +
        row[0].topChannelCode +
        "']"
      )
      .attr("selected", true);
    //初始化类型
    div
      .find(
        "select[name='deliveryType'] option[value='" +
        row[0].deliveryType +
        "']"
      )
      .attr("selected", true);
    $(".yfChannel").remove();

    if (isEditProviderInfos) {
      getDeliveryProvider(row[0].id, row[0].topChannelCode);
      getDeliveryCommonProvider(row[0].id, row[0].topChannelCode);
    }


    $.openx.openLayer(
      [800, 600],
      "修改类型管理",
      div.html(),
      false,
      function () {
        if ($.openx.validation(formId)) {
          const topChannelCode = $("#" + formId)
            .find("select[name='topChannelCode'] option:selected")
            .val();
          var topChanneName = $("#" + formId)
            .find("select[name='topChannelCode'] option:selected")
            .text();
          $("#" + formId)
            .find("input[name='topChannelName']")
            .val(topChanneName);
          $("#" + formId)
            .find("input[name='id']")
            .val(row[0].id);
          var info = $.openx.getJsonObj(formId);
          var providerInfos = [];

          /**
           * 如果 isEditProviderInfos 为 true, 则校验数据
           */
          if (isEditProviderInfos) {
            if (!validateProviderInfo()) {
              return false;
            }
            const { specialValues = [], commonValues = [] } = getDeliveryProviderValues();
            commonVaues = convertCommonProviderToInfoUtil(commonValues, row[0].id, topChannelCode);
            providerInfos = convertProviderFormToInfosUtil(
              specialValues,
              row[0].id
            );
            batchUpdate({ specialInfo: providerInfos, commonInfo: commonVaues, deliveryTypeId: row[0].id });
            return;
          }
          update(info);
        }
      }
    );

    if (isEditProviderInfos) {
      $('#deliveryEditModalInfoSection').hide();
      showDeliveryProviderWithInit();
    } else {
      $('#deliveryEditModalInfoSection').show();
      hideDeliveryProvider();
    }

  });
}

/**修改物流操作 */
$.openx.update = function () {
  $.openx.onClickUpdate(updateHandler);
};

$.openx.insert = function () {
  var formId = "addDeliveryTypeForm";
  var innerHtml = $.openx.innerHtml("addUpdateTpl");
  laytpl(innerHtml).render({}, function (html) {
    var topchannelDiv = $("div[name='channelPluginsDiv']").html();
    var providerPluginsDiv = $("div[name='providerSelectsPluginsDiv']").html();
    var div = $(html);
    div.find("div[name='topChannelTypeDiv']").html(topchannelDiv); // 设置渠道信息
    div.find("div[name='providerPluginsDiv']").html(providerPluginsDiv); // 设置物流供应商信息
    $.openx.openLayer(
      [800, 600],
      "新增类型管理",
      div.html(),
      false,
      function () {
        if ($.openx.validation(formId)) {
          var topChanneName = $("#" + formId)
            .find("select[name='topChannelCode'] option:selected")
            .text();
          $("#" + formId)
            .find("input[name='topChannelName']")
            .val(topChanneName);
          if (
            $("#" + formId)
              .find("select[name='topChannelCode'] option:selected")
              .val()
              .trim().length === 0
          ) {
            layer.tips(
              "请选择所属渠道",
              '#addDeliveryTypeForm div[name="topChannelTypeDiv"]',
              {
                tips: [2, "#78BA32"],
              }
            );
            return false;
          }
          var info = $.openx.getJsonObj(formId);
          var providerInfos = [];
          // if (info.isAppointProvider === "true") {
          //   if (!validateProviderInfo()) {
          //     return false;
          //   }
          //   providerInfos = convertProviderFormToInfosUtil(
          //     getDeliveryProviderValues()
          //   );
          // }
          save(info);
        }
      }
    );
    hideDeliveryProvider();
  });
};

/**
 * @param bean  入参对象bean
 * @param operationType  =    INSERT OR UPDATE
 */
function createOrUpdateDeliveryType(info, providerInfos, operationType) {
  $X("/logistics/deliverytype", "createOrUpdateDeliveryType").callx({
    info: info,
    providerInfos: providerInfos,
    operationType: operationType,
    onResult: function (data) {
      if (data) {
        $.openx.tableRefresh(null, null, true);
        layer.closeAll();
      }
    },
    onError: function (error) {
      var res = JSON.parse(error);
      layer.msg(res.message);
    },
  });
}

function save(info) {
  $X("/logistics/deliverytype", "save").callx({
    info: info,
    providerInfos: [],
    onResult: function (data) {
      if (data) {
        $.openx.tableRefresh(null, null, true);
        layer.closeAll();
      }
    },
    onError: function (error) {
      var res = JSON.parse(error);
      layer.msg(res.message);
    },
  });
}

function update(info) {
  $X("/logistics/deliverytype", "update").callx({
    info: info,
    providerInfos: [],
    onResult: function (data) {
      if (data) {
        $.openx.tableRefresh(null, null, true);
        layer.closeAll();
      }
    },
    onError: function (error) {
      var res = JSON.parse(error);
      layer.msg(res.message);
    },
  });
}

// 更新个性化配置
function batchUpdateSpecial(typeProviderRules) {
  return new Promise((resolve, reject) => {
    $X("/logistics/lgtTypeProviderRuleService", "batchSave").callx({
      typeProviderRules,
      onResult: function (data) {
        resolve(data);
        // if (data) {
        //   $.openx.tableRefresh(null, null, true);
        //   layer.closeAll();
        // }
      },
      onError: function (error) {
        var res = JSON.parse(error);
        // layer.msg(res.message);
        reject(new Error(res.message));
      },
    });
  })
}

// 更新通用配置
function batchUpdateCommon(deliveryTypeId, typeProviderCommonRules = []) {
  return new Promise((resolve, reject) => {
    $X("/logistics/lgtTypeProviderCommonRuleService", "batchSave").callx({
      deliveryTypeId,
      typeProviderCommonRules,
      onResult: function (data) {
        resolve(data);
        // if (data) {
        // $.openx.tableRefresh(null, null, true);
        // layer.closeAll();
        // }
      },
      onError: function (error) {
        var res = JSON.parse(error);
        // layer.msg(res.message);
        reject(new Error(res.message));
      },
    });
  })
}

// 更新通用配置和个性化配置
function batchUpdate({ specialInfo, commonInfo, deliveryTypeId }) {
  Promise.all([batchUpdateCommon(deliveryTypeId, commonInfo), batchUpdateSpecial(specialInfo)]).then(() => {
    layer.closeAll();
    layer.msg('类型配置更新成功', { icon: 1 });
    $.openx.tableRefresh(null, null, true);
  }).catch(err => {
    console.log('err', err);
    layer.msg(err.message);
  });
}

function showDeliveryProvider() {
  $("#deliveryProvider").show();
}

function showDeliveryProviderWithInit() {
  $("#deliveryProvider").show();
  // // 创建通用设置
  // createCommonConfig();
  // // 若不存在子渠道，则自动创建一个子渠道
  // createInitChildChannelIfNotChildChannel();
  var length = $(".yfChannel").length;
  if (length === 0) {
    var firstChildChannelDataId = $("#deliveryProvider .child-channel")
      .eq(0)
      .attr("data-id");
    initChannelCodeTree({ channelCodeId: firstChildChannelDataId });
  }
}

function hideDeliveryProvider() {
  $("#deliveryProvider").hide();
}

// 获取渠道物流公司配置表单数据
function getDeliveryProviderValues() {
  /**
   * 获取通用配置 
   */
  const commonValues = [];
  const commonWrapEle = $('#deliveryProvider #deliveryProviderCommon');
  // 抢单方式
  const commonRobType = $(commonWrapEle).find(`.delivery-provider-common-rob input[name="child-channel-time-rob-radio-${BASIC_CONSTANTS.comminConfigChannelTimeId}"]:checked`).val();
  // 物流公司列表
  const commonProviders = [];
  $(commonWrapEle).find(
    ".child-channel-time-list .child-channel-time-list-item:not(.child-channel-time-list-header)"
  )
    .each((_index, listItemEle) => {
      const listItemEleDataId = $(listItemEle).attr("data-id");
      // 物流公司
      const company = $(listItemEle)
        .find(
          '.child-channel-time-list-item-company select[name="logisticsType"]'
        )
        .val();
      // 范围
      const range = $(listItemEle)
        .find(".child-channel-time-list-item-range input")
        .val();
      // 等待接单时间
      const waitingTime = $(listItemEle)
        .find(".child-channel-time-list-item-waiting-time input")
        .val();
      commonProviders.push({
        id: listItemEleDataId,
        company,
        range,
        waitingTime,
      });
    });
  commonValues.push({
    providers: commonProviders,
    scrambleType: commonRobType,
  });

  /**
   * 获取个性化配置
   */
  const specialValues = [];
  $("#deliveryProvider #deliveryProviderSection .child-channel").each((_index, childEle) => {
    const childEleDataId = $(childEle).attr("data-id");
    const childEleDataSortNum = $(childEle).attr("data-sort-num");
    // 子渠道列表
    const channels = $(childEle)
      .find(".child-channel-input")
      .yfChannel("getData")
      .map((item) => ({
        channelCode: item.displayChannel,
        channelName: item.displayChannelName,
      }));
    // 时间段列表
    const times = [];
    $(childEle)
      .find(".child-channel-time")
      .each((_index1, childTimeEle) => {
        const childTimeEleDataId = $(childTimeEle).attr("data-id");
        const childTimeEleId = childTimeEleDataId.replace(/^child-channel-time-/, '');
        // 开始时间
        const startTime = $(childTimeEle)
          .find(".child-channel-time-header-time-input")
          .eq(0)
          .val();
        // 结束时间
        const endTime = $(childTimeEle)
          .find(".child-channel-time-header-time-input")
          .eq(1)
          .val();
        // 抢单方式
        const scrambleType = $(childTimeEle)
          .find(`.child-channel-time-rob input[name="child-channel-time-rob-radio-${childTimeEleId}"]:checked`)
          .val();
        // 物流公司列表
        const providers = [];
        $(childTimeEle)
          .find(
            ".child-channel-time-list .child-channel-time-list-item:not(.child-channel-time-list-header)"
          )
          .each((_index2, listItemEle) => {
            const listItemEleDataId = $(listItemEle).attr("data-id");
            // 物流公司
            const company = $(listItemEle)
              .find(
                '.child-channel-time-list-item-company select[name="logisticsType"]'
              )
              .val();
            // 范围
            const range = $(listItemEle)
              .find(".child-channel-time-list-item-range input")
              .val();
            // 等待接单时间
            const waitingTime = $(listItemEle)
              .find(".child-channel-time-list-item-waiting-time input")
              .val();
            providers.push({
              id: listItemEleDataId,
              company,
              range,
              waitingTime,
            });
          });
        times.push({ id: childTimeEleDataId, scrambleType, startTime, endTime, providers });
      });
    specialValues.push({
      id: childEleDataId,
      sortNum: +childEleDataSortNum,
      channels,
      times,
    });
  });

  return { specialValues, commonValues };
}

// 校验渠道物流公司配置表单数据
function validateProviderInfo() {
  // 获取到的渠道物流公司配置表单数据
  const { specialValues: providerValues = [], commonValues = [] } = getDeliveryProviderValues();
  if (!(providerValues.length > 0 || commonValues.length >= 0)) {
    // layer.msg('')
    return false;
  }

  /**
   * 通用配置校验
   */
  // 通用配置物流列表
  const commonProviderList = commonValues[0] && commonValues[0].providers;
  if (commonProviderList.length > 0) {
    // 校验物流公司是否为空
    const isValidCommonCompanyFail = commonProviderList.some((provider) => {
      const providerEle = $(
        `#deliveryProvider #deliveryProviderCommon .child-channel-time-list [data-id="${provider.id}"]`
      );
      if (!provider.company) {
        layer.tips(
          "请选择物流公司",
          providerEle.find(".child-channel-time-list-item-company"),
          {
            tips: [2, "#78BA32"],
          }
        );
        return true;
      }
      return false;
    });
    if (isValidCommonCompanyFail) {
      return false;
    }

    // 校验物流公司是否存在重叠
    const commonProviderCompanys = commonProviderList.map(item => item.company);
    if (new Set(commonProviderCompanys).size !== commonProviderList.length) {
      layer.tips(
        "物流公司重复",
        $(
          `#deliveryProvider #deliveryProviderCommon .child-channel-time-list-header .child-channel-time-list-item-company`
        ),
        {
          tips: [2, "#78BA32"],
        }
      );
      return false;
    }
  }


  /**
   * 个性化配置校验
   */
  if (providerValues.length > 0) {
    // 所有子渠道
    const allChannels = providerValues.reduce((prev, curr) => {
      return prev.concat(curr.channels);
    }, []);
    const allChannelCodes = allChannels.map(item => item.channelCode);
    // 校验子渠道列表是否重复
    if (new Set(allChannelCodes).size !== allChannelCodes.length) {
      layer.tips(
        "子渠道列表重复",
        $(
          `#deliveryProvider #deliveryProviderSection [data-id="${providerValues[0].id}"] .child-channel-input`
        ),
        {
          tips: [2, "#78BA32"],
        }
      );
      return false;
    }
    //  表单是否校验失败
    const isValidFail = providerValues.some((child) => {
      if (!(child.channels.length > 0)) {
        layer.tips(
          "请选择子渠道",
          $(`#deliveryProvider #deliveryProviderSection [data-id="${child.id}"] .child-channel-input`),
          {
            tips: [2, "#78BA32"],
          }
        );
        return true;
      }
      // 校验时间段列表
      const isValidTimesFail = child.times.some((childTime) => {
        const headerTimeInputEle = $(
          `#deliveryProvider #deliveryProviderSection [data-id="${child.id}"] [data-id="${childTime.id}"] .child-channel-time-header-time-input`
        );
        if (!childTime.startTime) {
          layer.tips("开始时间不能为空", headerTimeInputEle.eq(0), {
            tips: [2, "#78BA32"],
          });
          return true;
        }
        if (!childTime.endTime) {
          layer.tips("结束时间不能为空", headerTimeInputEle.eq(1), {
            tips: [2, "#78BA32"],
          });
          return true;
        }
        // // 抢单方式
        // const robVal = $(
        //   `#deliveryProvider #deliveryProviderSection [data-id="${child.id}"] [data-id="${childTime.id}"] .child-channel-time-rob input[name="child-channel-time-rob-radio-${childTime.id.replace(/^child-channel-time-/, '')}"]:checked`
        // ).val();

        // console.log('robVal',robVal);
        // if (
        //   convertTimeToNumUtil(childTime.endTime) <=
        //   convertTimeToNumUtil(childTime.startTime)
        // ) {
        //   layer.tips("结束时间必须大于开始时间", headerTimeInputEle.eq(1), {
        //     tips: [2, "#78BA32"],
        //   });
        //   return true;
        // }
        // 校验物流公司列表字段是否为空
        const isValidProvidersFail = childTime.providers.some((provider) => {
          const providerEle = $(
            `#deliveryProvider #deliveryProviderSection [data-id="${child.id}"] [data-id="${childTime.id}"] .child-channel-time-list [data-id="${provider.id}"]`
          );
          if (!provider.company) {
            layer.tips(
              "请选择物流公司",
              providerEle.find(".child-channel-time-list-item-company"),
              {
                tips: [2, "#78BA32"],
              }
            );
            return true;
          }
          /**
           * 范围和等待接单时间为可选，无需 required 校验
           */
          // if (!provider.range) {
          //   layer.tips(
          //     "请输入范围",
          //     providerEle.find(".child-channel-time-list-item-range"),
          //     {
          //       tips: [2, "#78BA32"],
          //     }
          //   );
          //   return true;
          // }
          // if (!provider.waitingTime) {
          //   layer.tips(
          //     "请输入等待接单时间",
          //     providerEle.find(".child-channel-time-list-item-waiting-time"),
          //     {
          //       tips: [2, "#78BA32"],
          //     }
          //   );
          //   return true;
          // }
          return false;
        });

        if (isValidProvidersFail) {
          return true;
        }

        // 校验物流公司是否存在重叠
        const childTimeProvidersCompanys = childTime.providers.map(item => item.company);
        if (new Set(childTimeProvidersCompanys).size !== childTime.providers.length) {
          layer.tips(
            "物流公司重复",
            $(
              `#deliveryProvider #deliveryProviderSection [data-id="${child.id}"] [data-id="${childTime.id}"] .child-channel-time-list-header .child-channel-time-list-item-company`
            ),
            {
              tips: [2, "#78BA32"],
            }
          );
          return true;
        }
        return false;
      });

      if (isValidTimesFail) {
        return true;
      }

      // 是否存在重叠时间段
      const isValidCrossTimes = isCrossTimeRangeUtil(child.times);

      if (isValidCrossTimes) {
        layer.tips(
          "存在重叠时间段",
          $(`#deliveryProvider #deliveryProviderSection [data-id="${child.id}"] .child-channel-input`),
          {
            tips: [2, "#78BA32"],
          }
        );
        return true;
      }

      return false;
    });

    return !isValidFail;
  }

  return true;
}

function getDeliveryProvider(deliveryTypeId, topChannelCode) {
  $X("/logistics/lgtTypeProviderRuleService", "listByDeliveryTypeId").callx({
    deliveryTypeId,
    onResult: function (data) {
      if (data && data.length > 0) {
        convertProviderInfosToFormUtil(data).forEach((item) => {
          createChildChannel({ channelData: item });
        });
      }
    },
    onError: function (error) {
      var res = JSON.parse(error);
      layer.msg(res.message);
    },
  });
}

function getDeliveryCommonProvider(deliveryTypeId, topChannelCode) {
  $X("/logistics/lgtTypeProviderCommonRuleService", "listByDeliveryTypeId").callx({
    deliveryTypeId,
    onResult: function (data) {
      const commonData = convertCommonProviderInfosToFormUtil(data);
      createCommonConfig(commonData || {});
    },
    onError: function (error) {
      var res = JSON.parse(error);
      layer.msg(res.message);
    },
  });
}

function changeToChannelCode() {
  const topChannelCode = $("#addDeliveryTypeForm")
    .find("select[name='topChannelCode'] option:selected")
    .val();
  if (!topChannelCode) {
    return;
  }
  // 若不存在子渠道，则自动创建一个子渠道
  createInitChildChannelIfNotChildChannel();
  var options = {
    url: "/boss/channelService",
    method: "listChannelTree",
    refreshMethod: "refreshChannelTree",
    topChannelCode: topChannelCode,
    filter: "leaves",
    isSearch: true,
  };
  $("#deliveryProvider .child-channel").each(function () {
    const inputEle = $(this).find(".child-channel-input");
    const inputId = inputEle.attr("id");
    $(`#yfChannelWindow_${inputId}`).remove();
    inputEle.yfChannel(options);
  });
}

function delTr(rowId) {
  $("#" + rowId).remove();
}

function initChannelCodeTree({ channelCodeId, channelCodes = [] }) {
  var topChannelCode = $("#addDeliveryTypeForm")
    .find("select[name='topChannelCode'] option:selected")
    .val();
  if (!topChannelCode) {
    return;
  }
  $(`#${channelCodeId}`).yfChannel({
    url: "/boss/channelService",
    method: "listChannelTree",
    refreshMethod: "refreshChannelTree",
    topChannelCode: topChannelCode,
    filter: "leaves",
    isSearch: true,
    data: channelCodes.length > 0 ? channelCodes : undefined,
    edit: channelCodes.length > 0,
  });
}


// 创建通用配置
function createCommonConfig(info = {}) {
  // 是否已创建
  const isCreated = Array.from($(`#deliveryProvider #deliveryProviderCommon [data-id="child-channel-${BASIC_CONSTANTS.commonConfigChannelId}"`)).length > 0;
  if (isCreated) {
    return;
  }
  const robRadioHtlStr = `
    <div class="delivery-provider-common-title">通用设置</div>
    <div data-id="child-channel-${BASIC_CONSTANTS.commonConfigChannelId}">
      <div data-id="child-channel-time-${BASIC_CONSTANTS.comminConfigChannelTimeId}">
        <div class="delivery-provider-common-rob v-flex v-flex-align-center v-col-margin">
          <div class="v-row-title">抢单方式：</div>
          <div class="v-flex v-flex-align-center">
            ${ROB_RADIOS.map(item => `
              <div class="radio radio-info radio-inline">
                <input id="child-channel-time-rob-radio-${BASIC_CONSTANTS.comminConfigChannelTimeId}-${item.value}" name="child-channel-time-rob-radio-${BASIC_CONSTANTS.comminConfigChannelTimeId}" value=${item.value} type="radio" />
                <label for="child-channel-time-rob-radio-${BASIC_CONSTANTS.comminConfigChannelTimeId}-${item.value}">${item.label}</label>
              </div>`).join('')}
          </div>
        </div>
        <div class="v-col-margin child-channel-time-list">
          <div class="v-flex v-flex-align-center child-channel-time-list-item child-channel-time-list-header">
            <div class="v-flex v-flex-center child-channel-time-list-item-company">物流公司</div>
            <div class="v-flex v-flex-center child-channel-time-list-item-range">范围</div>
            <div class="v-flex v-flex-center child-channel-time-list-item-waiting-time">等待接单时间</div>
            <div class="v-flex v-flex-center child-channel-time-list-item-operate">操作</div>
          </div>
          <div class="v-flex v-flex-center child-channel-time-list-top-extra">
            <i class="v-btn-text glyphicon glyphicon-plus child-channel-time-list-item-add" />
          </div>
        </div>
      </div>
    </div>
  `;
  $('#deliveryProviderCommon').append(robRadioHtlStr);

  // 设置抢单方式，默认为 close
  const realScrambleType = info.scrambleType || ROB_RADIOS[0].value;
  $(`#child-channel-time-rob-radio-${BASIC_CONSTANTS.comminConfigChannelTimeId}-${realScrambleType}`).attr("checked", "checked");

  // 事件委托
  $(
    `[data-id="child-channel-${BASIC_CONSTANTS.commonConfigChannelId}"] [data-id="child-channel-time-${BASIC_CONSTANTS.comminConfigChannelTimeId}"] .child-channel-time-list`
  )
    .off()
    .on("click", (e) => {
      if ($(e.target).hasClass("child-channel-time-list-item-add")) {
        createChildChannelTimeProvider({
          channelId: BASIC_CONSTANTS.commonConfigChannelId,
          channelTimeId: BASIC_CONSTANTS.comminConfigChannelTimeId,
          providerData: INIT_PROVIDER_CONFIG_PROVIDER,
        });
        $('#deliveryProvider #deliveryProviderCommon .child-channel-time-list-top-extra').css('display', 'none');
      } else if ($(e.target).hasClass("child-channel-time-list-item-del")) {
        const listItemId = $(e.target)
          .attr("data-id")
          .replace(
            /^child-channel-time-list-item-del-/,
            "child-channel-time-list-item-"
          );
        $(
          `[data-id="child-channel-${BASIC_CONSTANTS.commonConfigChannelId}"] [data-id="child-channel-time-${BASIC_CONSTANTS.comminConfigChannelTimeId}"] [data-id="${listItemId}"]`
        ).remove();
        const childChannelTimeList = Array.from($('#deliveryProvider #deliveryProviderCommon .child-channel-time-list .child-channel-time-list-item:not(.child-channel-time-list-header)'));
        if (childChannelTimeList.length === 0) {
          $('#deliveryProvider #deliveryProviderCommon .child-channel-time-list-top-extra').css('display', 'flex');
        }
      }
    });

  /**
   * 创建物流公司列表
   */
  if (info.providers && info.providers.length > 0) {
    info.providers.forEach(item => {
      createChildChannelTimeProvider({ channelId: BASIC_CONSTANTS.commonConfigChannelId, channelTimeId: BASIC_CONSTANTS.comminConfigChannelTimeId, providerData: item });
    })
  } else {
    createChildChannelTimeProvider({ channelId: BASIC_CONSTANTS.commonConfigChannelId, channelTimeId: BASIC_CONSTANTS.comminConfigChannelTimeId });
  }
}

// 点击子渠道列表新增物流公司
function createChildChannelTimeProvider({
  channelId,
  channelTimeId,
  providerData: { company = "", range = "", waitingTime = "" } = {},
} = {}) {
  const dataId = window.uuidv4();
  const htmlStr = `
    <div data-id="child-channel-time-list-item-${dataId}" class="v-flex v-flex-align-center child-channel-time-list-item">
      <div class="v-flex v-flex-center child-channel-time-list-item-company">${$(
    "div[name='providerSelectsPluginsDiv']"
  ).html()}</div>
      <div class="v-flex v-flex-center child-channel-time-list-item-range">
        <input type="number" class="layui-input child-channel-time-list-item-range-input" />
        <span style="white-space:nowrap;padding-left:8px;">公里之内</span>
      </div>
      <div class="v-flex v-flex-center child-channel-time-list-item-waiting-time">
        <input type="number" class="layui-input child-channel-time-list-item-waiting-time-input" />
        <span style="white-space:nowrap;padding-left:8px;">分钟</span>
      </div>
      <div class="v-flex v-flex-center child-channel-time-list-item-operate">
        <i class="v-btn-text glyphicon glyphicon-plus child-channel-time-list-item-add" />
        <i data-id="child-channel-time-list-item-del-${dataId}" class="v-btn-text glyphicon glyphicon-minus child-channel-time-list-item-del" />
      </div>
    </div>
  `;
  $(
    `[data-id="child-channel-${channelId}"] [data-id="child-channel-time-${channelTimeId}"] .child-channel-time-list`
  ).append(htmlStr);
  const listItemEle = $(
    `[data-id="child-channel-${channelId}"] [data-id="child-channel-time-${channelTimeId}"] [data-id="child-channel-time-list-item-${dataId}"]`
  );
  $(listItemEle)
    .find('.child-channel-time-list-item-company select[name="logisticsType"]')
    .val(company);
  $(listItemEle).find(".child-channel-time-list-item-range input").val(range);
  $(listItemEle)
    .find(".child-channel-time-list-item-waiting-time input")
    .val(waitingTime);
}

// 点击子渠道新增时间
function createChildChannelTime({
  channelId,
  timeData: { startTime = "", endTime = "", scrambleType = "", providers = [] } = {},
} = {}) {
  const childId = window.uuidv4();
  const htmlStr = `
    <div data-id="child-channel-time-${childId}" class="child-channel-time v-col-margin">
      <div class="child-channel-time-header v-flex v-flex-align-center v-flex-justify-between">
        <div class="v-flex v-flex-align-center child-channel-time-header-picker">
          <div class="v-row-title">时间</div>
          <input class="layui-input child-channel-time-header-time-input" placeholder="开始时间" type="time" step="1">
          <div style="padding: 0 8px;">到</div>
          <input class="layui-input child-channel-time-header-time-input" placeholder="结束时间" type="time" step="1">
        </div>
        <div class="v-flex v-flex-align-center child-channel-time-header-operate">
          <div class="child-channel-time-header-add v-btn-text">新增时间</div>
          <div data-id="child-channel-time-header-del-${childId}" class="child-channel-time-header-del v-btn-text">删除</div>
        </div>
      </div>
      <div class="child-channel-time-rob v-col-margin v-flex v-flex-align-center">
        <div class="v-row-title">抢单方式：</div>
        <div class="v-flex v-flex-align-center">
        ${ROB_RADIOS.map(item => `
          <div class="radio radio-info radio-inline">
            <input id="child-channel-time-rob-radio-${childId}-${item.value}" name="child-channel-time-rob-radio-${childId}" value=${item.value} type="radio" />
            <label for="child-channel-time-rob-radio-${childId}-${item.value}">${item.label}</label>
          </div>
        `).join('')}
        </div>
      </div>
      <div class="v-col-margin child-channel-time-list">
        <div class="v-flex v-flex-align-center child-channel-time-list-item child-channel-time-list-header">
          <div class="v-flex v-flex-center child-channel-time-list-item-company">物流公司</div>
          <div class="v-flex v-flex-center child-channel-time-list-item-range">范围</div>
          <div class="v-flex v-flex-center child-channel-time-list-item-waiting-time">等待接单时间</div>
          <div class="v-flex v-flex-center child-channel-time-list-item-operate">操作</div>
        </div>
      </div>
    </div>
	`;
  $(`[data-id="child-channel-${channelId}"] .child-channel-times`).append(
    htmlStr
  );

  // 设置开始时间/结束时间
  const timeInputEles = $(
    `[data-id="child-channel-${channelId}"] [data-id="child-channel-time-${childId}"] .child-channel-time-header-time-input`
  );
  timeInputEles.eq(0).val(startTime);
  timeInputEles.eq(1).val(endTime);
  /**
   * 设置抢单方式
   * 若 scrambleType 为空，则取 通用配置抢单方式
   */
  const realScrambleType = scrambleType || $(`#deliveryProvider #deliveryProviderCommon .delivery-provider-common-rob input[name="child-channel-time-rob-radio-${BASIC_CONSTANTS.comminConfigChannelTimeId}"]:checked`).val() || ROB_RADIOS[0].value;
  $(`#child-channel-time-rob-radio-${childId}-${realScrambleType}`).attr("checked", "checked")

  // 事件委托
  $(
    `[data-id="child-channel-${channelId}"] [data-id="child-channel-time-${childId}"] .child-channel-time-list`
  )
    .off()
    .on("click", (e) => {
      if ($(e.target).hasClass("child-channel-time-list-item-add")) {
        createChildChannelTimeProvider({
          channelId,
          channelTimeId: childId,
          providerData: INIT_PROVIDER_CONFIG_PROVIDER,
        });
      } else if ($(e.target).hasClass("child-channel-time-list-item-del")) {
        const listItemId = $(e.target)
          .attr("data-id")
          .replace(
            /^child-channel-time-list-item-del-/,
            "child-channel-time-list-item-"
          );
        $(
          `[data-id="child-channel-${channelId}"] [data-id="child-channel-time-${childId}"] [data-id="${listItemId}"]`
        ).remove();
      }
    });
  // 插入物流公司列表
  providers.forEach((providerData) => {
    createChildChannelTimeProvider({
      channelId,
      channelTimeId: childId,
      providerData,
    });
  });
}

// 点击新增子渠道
function createChildChannel({
  channelData: { sortNum, channels = [], times = [] } = {},
} = {}) {
  const childId = window.uuidv4();
  let childSortNum = sortNum;
  if (!childSortNum) {
    // 最后一个元素 sortNum
    const lastChildSortNum = $(
      "#deliveryProvider #deliveryProviderSection .child-channel:last-child"
    ).attr("data-sort-num");
    childSortNum = lastChildSortNum ? +lastChildSortNum + 1 : 1;
  }
  const htmlStr = `
    <div data-sort-num="${childSortNum}" data-id="child-channel-${childId}" class="child-channel v-col-margin-lg">
			<div class="v-flex v-flex-align-center v-flex-justify-between">
        <div class="v-flex v-flex-align-center">
          <div class="v-row-title child-channel-sort-num">${numToStringByAddZeroUtil(
    childSortNum
  )}</div>
				  <div class="v-row-title">子渠道</div>
          <div class="v-flex v-flex-align-center">
            <input
              id="child-channel-input-${childId}"
              class="layui-input form-control child-channel-input"
              type="text"
              readonly
            />
          </div>
				</div>
        <div data-id="child-channel-del-${childId}" class="v-btn-text child-channel-del">删除</div>
			</div>
			<div class="child-channel-times"></div>
		</div> 
	`;
  $("#deliveryProviderSection").append(htmlStr);

  initChannelCodeTree({
    channelCodeId: `child-channel-input-${childId}`,
    channelCodes: channels.map((item) => item.channelCode),
  });
  $(`[data-id="child-channel-${childId}"] .child-channel-input`).val(
    `${channels.length}个选中项`
  );
  // 事件委托
  $(`[data-id="child-channel-${childId}"]`)
    .off()
    .on("click", (e) => {
      if ($(e.target).hasClass("child-channel-del")) {
        const toDeledchildChannelId = $(e.target)
          .attr("data-id")
          .replace(/^child-channel-del-/, "child-channel-");
        $(`[data-id="${toDeledchildChannelId}"]`).remove();
      } else if ($(e.target).hasClass("child-channel-time-header-add")) {
        createChildChannelTime({
          channelId: childId,
          timeData: Object.assign({}, INIT_PROVIDER_CONFIG_TIME, {
            startTime: "00:00:00",
            endTime: "00:00:00",
          }),
        });
      } else if ($(e.target).hasClass("child-channel-time-header-del")) {
        const childChannelTimeId = $(e.target)
          .attr("data-id")
          .replace(/^child-channel-time-header-del-/, "child-channel-time-");
        $(
          `[data-id="child-channel-${childId}"] [data-id="${childChannelTimeId}"]`
        ).remove();
      }
    });
  // 插入时间段列表
  times.forEach((timeData, index) => {
    createChildChannelTime({
      channelId: childId,
      timeData: Object.assign({}, timeData, {
        startTime: timeData.startTime || "00:00:00",
        endTime: timeData.endTime || (index === 0 ? "23:59:59" : "00:00:00"),
      }),
    });
  });
}

// 创建一个初始子渠道
function createInitChildChannel() {
  createChildChannel({ channelData: INIT_PROVIDER_CONFIG_CHILD_CHANNEL });
}

// 若不存在子渠道，则自动创建一个子渠道
function createInitChildChannelIfNotChildChannel() {
  const childChannels = Array.from($(`#deliveryProvider #deliveryProviderSection .child-channel`));
  if (!(childChannels && childChannels.length > 0)) {
    createInitChildChannel();
  }
}
